package com.hrm.attendance.service;

import com.hrm.attendance.dao.ArchiveMonthlyDao;
import com.hrm.attendance.dao.ArchiveMonthlyInfoDao;
import com.hrm.attendance.dao.AttendanceDao;
import com.hrm.attendance.dao.UserDao;
import com.hrm.common.util.IdWorker;
import com.hrm.domain.attendance.entity.ArchiveMonthly;
import com.hrm.domain.attendance.entity.ArchiveMonthlyInfo;
import com.hrm.domain.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ArchiveService {

    @Autowired
    private ArchiveMonthlyDao archiveMonthlyDao;
    @Autowired
    private ArchiveMonthlyInfoDao archiveMonthlyInfoDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AttendanceDao attendanceDao;

    public void saveArchive(String archiveDate,String companyId) {
        //查询企业内所有用户
        List<User> users = userDao.findByCompanyId(companyId);
        //保存归档主表
        ArchiveMonthly archiveMonthly = new ArchiveMonthly();
        archiveMonthly.setId(idWorker.nextId()+"");
        archiveMonthly.setCompanyId(companyId);
        archiveMonthly.setArchiveYear(archiveDate.substring(0,4));
        archiveMonthly.setArchiveMonth(archiveDate.substring(5));
        archiveMonthly.setTotalPeopleNum(users.size());        //总人数
        archiveMonthly.setFullAttePeopleNum(users.size());      //全勤的人，这里认为所有人都全勤
        archiveMonthly.setIsArchived(0);  //0是已经归档
        archiveMonthlyDao.save(archiveMonthly);
        //保存归档明细表
        for (User user : users) {
            ArchiveMonthlyInfo info = new ArchiveMonthlyInfo(user);
            //统计每个用户的考勤记录(出勤多少天、矿工多少天、、、)
            Map<String, Object> map = attendanceDao.countNum(user.getId(), archiveDate + "%");
            info.setStatisData(map);
            info.setArchiveDate(archiveDate);
            info.setId(idWorker.nextId()+"");
            info.setAtteArchiveMonthlyId(archiveMonthly.getId());
            archiveMonthlyInfoDao.save(info);
        }

    }

    public List<ArchiveMonthly> getYearReport(String year, String companyId) {
        return archiveMonthlyDao.findByCompanyIdAndArchiveYear(companyId,year);
    }


    public List<ArchiveMonthlyInfo> getReportInfo(String yearMonth, String companyId) {
        String year = yearMonth.substring(0,3);
        String month = yearMonth.substring(4);
        ArchiveMonthly monthly = archiveMonthlyDao.findByCompanyIdAndArchiveYearAndArchiveMonth(companyId, year, month);
        return archiveMonthlyInfoDao.findByAtteArchiveMonthlyId(monthly.getId());
    }

    public ArchiveMonthlyInfo findUserIdArchiveDetail(String userId, String yearMonth) {
        return archiveMonthlyInfoDao.findByUserIdAndArchiveDate(userId,yearMonth);
    }
}
